package com.base.service.workflow.service.impl;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.core.framework.sql.service.impl.SqlBaseServiceImplV1Ext;
import com.base.core.head.constants.CodeResVal;
import com.base.core.head.enums.TaskTypeEnum;
import com.base.service.workflow.dao.FlowDao;
import com.base.service.workflow.entity.FlowDO;
import com.base.service.workflow.entity.TaskDO;
import com.base.service.workflow.service.FlowService;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.head.exception.BusinessException;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.query.QueryWrapper;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.update.UpdateWrapper;

/**
 * @author start 
 */
@Service("flowService")
public class FlowServiceImpl extends SqlBaseServiceImplV1Ext<FlowDO, Long> implements FlowService {

	private FlowDao flowDao;

	public FlowServiceImpl(@Qualifier("flowDao") FlowDao flowDao) {
		super(flowDao);
		this.flowDao = flowDao;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public FlowDO nextFlow(Long processId,Long parentFlowId,TaskDO task, JsonObject variables) {
		// if this is end event element, then update process status as FINISHED
		if (task.getTaskType() != TaskTypeEnum.END_EVENT) {
			// create next flow
			FlowDO nextFlow = new FlowDO();
			nextFlow.setProcessId(processId);
			nextFlow.setParentId(parentFlowId);
			nextFlow.setTaskId(task.getId());
			nextFlow.setVariables(variables);
			nextFlow.setFinished(0L);
			save(nextFlow);
			return nextFlow;
		}
		return null;
	}

	@Override
	public void setFinished(Long flowId) {
		UpdateWrapper wrapper=new UpdateWrapper();
		wrapper
			.eq("id", flowId)
			.set("finished", flowDao.getSnowflakeIdWorkerNextId());
		if(flowDao.executeUpdate(wrapper)!=1) {
			throw new BusinessException(CodeResVal.CODE_10005);
		}
	}

	@Override
	public FlowDO getCurrentActiveFlow(Long processId) {
		QueryWrapper wrapper=new QueryWrapper();
		wrapper.eq("processId", processId).eq("finished", 0L);
		return get(flowDao.queryForList(wrapper));
	}

}
